package com.rtmart.imageupload.controller.user;

import com.rtmart.imageupload.entity.Admin;
import com.rtmart.imageupload.entity.User;
import com.rtmart.imageupload.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user/")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @GetMapping("edit")
    public String showUser(HttpSession httpSession, Model model){
        User user = (User)httpSession.getAttribute("user");
        model.addAttribute("user", user);
        return "user/edit";
    }
    @PostMapping("edit")
    @Transactional
    public String updateUser(@Validated(value = {Admin.class}) User user, BindingResult bindingResult, HttpSession httpSession, RedirectAttributes model){
        if (bindingResult.hasErrors()){
            return "user/edit";
        }
        if (1 == userRepository.updateUser(user.getName(),user)){
            httpSession.setAttribute("user",user);
            model.addFlashAttribute("message","修改成功");
        } else {
            model.addFlashAttribute("errorMessage","修改失败");
        }
        return "redirect:/";
    }

}
